﻿using CommunityToolkit.Mvvm.ComponentModel;
using Microsoft.Extensions.Logging;
using ShanNiang.AutoUpdate.Service.Interfaces;
using ShanNiang.AutoUpdate.Service.Responses;
using ShanNiang.AutoUpdate.Service;
using Microsoft.Extensions.Options;
using CommunityToolkit.Mvvm.Input;
using HandyControl.Controls;
using System.Diagnostics;
using Serilog;
using Serilog.Core;
using System.Reflection;
using System.IO;


namespace ShanNiang.AutoUpdate
{

    public partial class MainWindowViewModel : ObservableObject
    {
        private readonly ICheckVersionService _checkVersionService;
        private readonly IUpdateService _updateService;
        private readonly AutoUpdateConfig _autoUpdateConfig;
        private readonly ILogger<MainWindow> _logger;
        //public PublishedClientResponse? RemoteClientResponse { get; set; }
        public MainWindowViewModel(IOptions<AutoUpdateConfig> configuration, ICheckVersionService checkVersionService, IUpdateService updateService, ILogger<MainWindow> logger)
        {
            _autoUpdateConfig = configuration.Value;
            _checkVersionService = checkVersionService;
            _updateService = updateService;
            _logger = logger;
        }
        /// <summary>
        /// 本地版本
        /// </summary>
        [ObservableProperty]
        private string? _localVersion;
        /// <summary>
        /// 是否需要升级
        /// </summary>
        [ObservableProperty]
        private bool _needUpdate;
        /// <summary>
        /// 远程版本
        /// </summary>
        [ObservableProperty]
        private string? _remoteVersion;
        /// <summary>
        /// 正在升级
        /// </summary>
        [ObservableProperty]
        private bool _working;
        /// <summary>
        /// 退出
        /// </summary>
        [RelayCommand]
        private void ByeBye()
        {
            Environment.Exit(0);
        }
        /// <summary>
        /// 加载
        /// </summary>
        /// <returns></returns>
        [RelayCommand]
        private async Task LoadedAsync()
        {
            _logger.LogDebug($"检测版本。。");
            var assembly = typeof(MainWindowViewModel).Assembly;
            var mainProcessFileName = Path.Combine(Environment.CurrentDirectory, $"{_autoUpdateConfig.MainProcessName}.dll");
            if (Path.Exists(mainProcessFileName))
            {
                assembly = Assembly.LoadFrom(mainProcessFileName);
            }
            var localVersion = _checkVersionService.GetLocalVersion(assembly);
            LocalVersion = localVersion.ToString();
            var response = await _checkVersionService.GetRemoteVersionAsync();
            RemoteVersion = response == null ? "0.0.0.0" : response.RemoteVersion.ToString();
            if (response != null && localVersion.CompareTo(response.RemoteVersion) < 0)
            {

                Process.GetProcessesByName(_autoUpdateConfig.MainProcessName).ToList().ForEach(p => p.Kill());
                NeedUpdate = true;
                Working = true;
                await DoUpdate(response);
                Working = false;
                Environment.Exit(0);
            }
            else
            {
                _logger.LogDebug($"版本足够新，不用更新。Local:{localVersion};Remote{response?.RemoteVersion};");
            }
        }

        private async Task DoUpdate(PublishedClientResponse remoteClientResponse)
        {
            if (remoteClientResponse != null && remoteClientResponse.Url != null)
            {
                try
                {
                    var packagePath = await _updateService.DownloadPackageAsync(remoteClientResponse.Url, remoteClientResponse.RemoteVersion);
                    _checkVersionService.SetLocalVersion(remoteClientResponse.RemoteVersion.ToString());
                    MessageBox.Show("升级包下载成功");
                    _updateService.DoUpdate(packagePath);
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "升级时报错");
                }
            }
        }
    }
}
